﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommonLib {
    public struct AAGrid {
        public AABBox boundary;
        public int size;
        public Vector3c diff, rdiff;
        public List<Primitive>[] grid;

        public AAGrid(AABBox _boundary, int _size) {
            this.boundary = _boundary;
            this.size = _size;
            this.diff = _boundary.dims;
            this.diff.div(_size);
            this.rdiff = new Vector3c(1, 1, 1);
            this.rdiff.div(this.diff);
            this.grid = new List<Primitive>[_size * _size * _size];
        }

        public void DeployPrimitives(Primitive[] primitives) {
            for (uint i = 0; i < grid.Length; i++)
                grid[i] = new List<Primitive>();

            for (uint i = 0; i < primitives.Length; i++) {
                AABBox primBndry = primitives[i].getBoundingBox();
                Vector3c v1 = primBndry.vmin;
                v1.sub(boundary.vmin);
                v1.mul(rdiff);
                Vector3c v2 = primBndry.vmax;
                v2.sub(boundary.vmin);
                v2.mul(rdiff);
                Int3 j1 = new Int3(v1);
                j1.crop(0, size);
                Int3 j2 = new Int3(v2);
                j2.x++; j2.y++; j2.z++;
                j2.crop(0, size);
                for (int z = j1.z; z < j2.z; z++)
                    for (int y = j1.y; y < j2.y; y++)
                        for (int x = j1.x; x < j2.x; x++) {
                            int idx = x + (y + z * size) * size;
                            Vector3c pos = new Vector3c(x, y, z);
                            pos.mul(diff);
                            pos.add(boundary.vmin);
                            AABBox cell = new AABBox(pos, diff);
                            if (primitives[i].isIntersect(cell) != Intersection.Intersecting)
                                continue;
                            grid[idx].Add(primitives[i]);
                        }
            }
        }
    }
}
